<?php
namespace Core\CoreComponents\ArticlesManager;

require_once(COMPONENTS_DIR . 'ArticlesManager/IArticles.php');
require_once(CONTRACTS_DIR . 'article.entity.php');

/**
* This interface provide all accessible methods on Articles module
*
* @method ServiceResponse getArticles()
*/
class Articles implements IArticles
{
	/**
	* Get all articles
	*
	* @return This response contains all articles
	*/
    public function getArticles()
	{
		Logger::Info("getArticles");
		
		$response = null;
		
		try
		{	
			$session = Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('Article');
			$result = $session->ListResult();
			
			$response = new ServiceResponse($result);

			$session->Close();

			Logger::Info("getArticles is finished");
		}
		catch (Exception $ex) 
		{
			$response = ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get online articles
	*
	* @return This response contains all online articles
	*/
    public function getOnlinesArticles()
	{
		Logger::Info("getOnlinesArticles");
		
		$response = null;
		
		try
		{	
			$session = Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('Article');
			$session->AddCriteria(Expression::SQL_EQ('State', 2));
			$result = $session->ListResult();
			
			$response = new ServiceResponse($result);

			$session->Close();

			Logger::Info("getOnlinesArticles is finished");
		}
		catch (Exception $ex) 
		{
			$response = ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Add an article
	*
	* @param string $title The article title
	* @param string $text The article content
	*
	* @return This response contains the added article
	*/
    public function addArticle($title, $text)
	{
		Logger::Info("addArticle $title, $text");
		
		$response = null;
		
		try
		{	
			$session = Session::Instance();
			$session->Open();
			
			$article = Article::Create($title, $text);
			
			$result = $session->Save($article);
			$response = new ServiceResponse($result);

			$session->Close();

			Logger::Info("addArticle is finished");
		}
		catch (Exception $ex) 
		{
			$response = ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
}

?> 